import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, from } from 'rxjs';
import { tap } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { CacheService } from './cache.service';
@Injectable({
  providedIn: 'root'
})
export class NetInterceptorService implements HttpInterceptor {
  constructor(
    private cacheService: CacheService,
    private nzmsg: NzMessageService,
    private router: Router
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.method === 'OPTIONS') { return next.handle(req); }
    const newReq = req.clone({
      headers: req.headers.set('vf', this.cacheService.getToken())
    });

    return next.handle(newReq).pipe(tap(
      data => this.handleOk(data),
      err => this.handlerError(err)
    ));
  }
  handleOk(data) {
    if (data instanceof HttpResponse && data.body['code'] === 0) {
      this.nzmsg.error(data.body['msg']);
    }
  }
  handlerError(err: HttpErrorResponse) {
    if (err instanceof HttpErrorResponse) {
      let msg = '';
      switch (err.status) {
        case 404:
          msg = '接口离家出走了！';
          break;
        case 401:
          msg = '未认证，请先登陆！';
          this.router.navigateByUrl('/login');
          break;
        case 403:
          msg = '认证失效，请先登陆！';
          this.router.navigateByUrl('/login');
          break;
        case 500:
        case 503:
          msg = '服务端出错！';
          break;
      }
      this.nzmsg.error(`[${err.status}] ${msg || err.message}`);
    }
  }
}
